package top.yihoxu.yapi.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import top.yihoxu.CurrentRequest;
import top.yihoxu.ResultResponse;
import top.yihoxu.client.ApiClient;
import top.yihoxu.yapi.common.BaseResponse;
import top.yihoxu.yapi.common.DeleteRequest;
import top.yihoxu.yapi.common.ErrorCode;
import top.yihoxu.yapi.common.ResultUtils;
import top.yihoxu.yapi.exception.BusinessException;
import top.yihoxu.yapi.exception.ThrowUtils;
import top.yihoxu.yapi.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import top.yihoxu.yapi.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import top.yihoxu.yapi.model.entity.InterfaceInfo;
import top.yihoxu.yapi.model.entity.User;
import top.yihoxu.yapi.model.vo.interfacevo.InterfaceInfoVO;
import top.yihoxu.yapi.model.vo.interfacevo.RequestParams;
import top.yihoxu.yapi.model.vo.interfacevo.ResponseParams;
import top.yihoxu.yapi.service.InterfaceInfoService;
import top.yihoxu.yapi.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author dth
 * @Date 2024/7/13 17:15
 * @PackageName:top.yihoxu.yapi.controller
 * @ClassName: InterfaceInfoController
 * @Description: 接口信息控制
 * @Version 1.0
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;


    // region 增删改查


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        String requestParams = interfaceInfo.getRequestParams();
        String responseParams = interfaceInfo.getResponseParams();
        List<RequestParams> requestList = JSONUtil.toList(requestParams, RequestParams.class);
        List<ResponseParams> responseList = JSONUtil.toList(responseParams, ResponseParams.class);
        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
        interfaceInfoVO.setRequestParams(requestList);
        interfaceInfoVO.setResponseParamsList(responseList);
        return ResultUtils.success(interfaceInfoVO);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    //endregion
    @PostMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(@RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService
                .page(new Page<>(current, size), interfaceInfoService
                        .getQueryWrapper(interfaceInfoQueryRequest));
        // 获取封装类
        return ResultUtils.success(interfaceInfoPage);

    }

    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest invokeRequest, HttpServletRequest request) {
        if (invokeRequest == null || invokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        System.out.println(invokeRequest);
        Long id = invokeRequest.getId();
        String requestParams = invokeRequest.getRequestParams();
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        String method = interfaceInfo.getMethod();
        String url = interfaceInfo.getUrl();
        //获取登录用户的 ak和sk
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        //创建客户端
        ApiClient apiClient = new ApiClient(accessKey, secretKey);
        CurrentRequest currentRequest = new CurrentRequest();
        currentRequest.setRequestParams(requestParams);
        currentRequest.setUrl(url);
        ResultResponse resultResponse = apiClient.sendRequest(currentRequest, apiClient);
        return ResultUtils.success(resultResponse);
    }
}
